import datetime
import os

import requests


def speech_to_text(audio_file_path):
    """
    使用SiliconFlow API将音频文件转换为文本
    """
    # 检查音频文件是否存在
    if not os.path.exists(audio_file_path):
        print(f"错误：音频文件不存在 - {audio_file_path}")
        return None

    url = "https://api.siliconflow.cn/v1/audio/transcriptions"

    try:
        # 正确打开音频文件
        with open(audio_file_path, 'rb') as audio_file:
            files = {"file": audio_file}
            payload = {"model": "TeleAI/TeleSpeechASR"}
            headers = {"Authorization": "Bearer sk-pjgenkdeoudivpnruwhnkysilysvgpurseenmmrvqgntxela"}

            print("正在发送请求到 SiliconFlow API...")
            response = requests.post(url, data=payload, files=files, headers=headers)
            response.raise_for_status()  # 如果响应状态码不是200会抛出异常

            return response.json()
    except requests.exceptions.ConnectionError:
        print("网络连接错误：无法连接到 SiliconFlow API")
        print("请检查网络连接或稍后再试")
        return None
    except requests.exceptions.Timeout:
        print("请求超时：连接 SiliconFlow API 超时")
        return None
    except requests.exceptions.RequestException as e:
        print(f"请求发生错误：{e}")
        return None
    except Exception as e:
        print(f"处理音频文件时发生错误：{e}")
        return None


def save_result_to_file(result, audio_file_path):
    """
    将识别结果保存到以时间戳命名的文本文件中
    """
    try:
        # 生成以时间戳命名的文件名
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        txt_filename = f"asr_result_{timestamp}.txt"

        # 获取音频文件所在目录
        audio_dir = os.path.dirname(audio_file_path)
        txt_file_path = os.path.join(audio_dir, txt_filename)

        # 提取识别结果中的文本
        if 'text' in result:
            text_content = result['text']
        else:
            # 如果响应结构不同，直接转换为字符串保存
            text_content = str(result)

        # 写入文件
        with open(txt_file_path, 'w', encoding='utf-8') as f:
            f.write(text_content)

        print(f"识别结果已保存到文件：{txt_file_path}")
        return txt_file_path
    except Exception as e:
        print(f"保存文件时发生错误：{e}")
        return None


def main():
    # 音频文件路径
    audio_file_path = r"C:\Users\黄威健\Videos\Captures\运输管理系统 .mp3"

    print(f"正在处理音频文件：{audio_file_path}")

    # 调用语音转文字函数
    result = speech_to_text(audio_file_path)

    if result:
        print("转换结果：")
        print(result)

        # 保存结果到文本文件
        save_result_to_file(result, audio_file_path)
    else:
        print("转换失败")


if __name__ == "__main__":
    main()
